package io.afu.dnspod.actions;

import com.alibaba.fastjson.JSON;
import io.afu.common.exception.BaseException;
import io.afu.dnspod.dto.Domain;
import io.afu.dnspod.dto.DomainRecords;
import io.afu.dnspod.dto.Record;
import io.afu.dnspod.dto.RecordResp;
import io.afu.httprequest.HttpRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Dnspod {

    private String tokenid; // 必填

    private String token; // 必填

    private String format = "json"; // 可选值

    private String errorNoEmpty = "no"; // 可选值

    private String userId; // 仅在代理接口的时候需要，用户独立方法API不需要，目前这个参数不做操作。

    public Dnspod(){

    }

    public Dnspod(String tokenid,String token){
        this.tokenid = tokenid;
        this.token = token;
    }

    public static Dnspod getInstance(){
        return new Dnspod();
    }

    public static Dnspod getInstance(String tokenid,String token){
        return new Dnspod(tokenid,token);
    }

    public String getTokenid() {
        return tokenid;
    }

    public void setTokenid(String tokenid) {
        this.tokenid = tokenid;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getFormat() {
        return format;
    }

    public void setFormat(String format) {
        this.format = format;
    }

    public String getErrorNoEmpty() {
        return errorNoEmpty;
    }

    public void setErrorNoEmpty(String errorNoEmpty) {
        this.errorNoEmpty = errorNoEmpty;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }


    public void updateDomainRecord(String domainName,String subdomain,String record){
        Domain targetDomain =null;
        DomainRecords domainRecords = DDomain.getDomainList(tokenid,token,format);
        List<Domain> domains = domainRecords.getDomains();
        for (Domain domain:domains){
            if (domain.getName().equals(domainName)){
                targetDomain = domain;
            }
        }
        if (targetDomain == null){
            // 这里能集成一个日志打印就OK了
            return;
        }
        RecordResp recordResp = DRecord.getRecordList(tokenid,token,format,targetDomain.getId().toString(),subdomain);
        List<Record> records = recordResp.getRecords();
        if (records == null || records.size() ==0 ){
            // 抛出一个找不到的错误
            return;
        }
        Record targetRecord = records.get(0);
        if (targetRecord.getValue().equals(record)){
            // 记录一个记录相同的日志，并不做任何的改动
            return;
        }
        Boolean stat = DRecord.updateRecord(tokenid,token,format,targetDomain.getId().toString(),subdomain,targetRecord.getId(),record);
    }





}
